<template>
  <div class="image-picker">
    <div class="image-picker__title">
      <p>{{ title }}</p>
      <p>{{ imageLength }}/{{ maxLength }}</p>
    </div>
    <div class="image-picker__description">{{ desc ? desc : `点击"+"添加图片，点击"x"删除图片最多上传${maxLength}张` }}</div>
    <div class="image-picker__content">
      <ul class="image-picker__content-list">
        <li
          v-for="(item, index) in files"
          :key="index"
          class="image-picker__content-list--item"
        >
          <img :src="item.src" alt="" />
          <div
            class="image-picker__content-list--item--del"
            @click="onImageClick(item.id)"
          >
            ｘ
          </div>
        </li>
        <li class="image-picker__content-list--item" @click="onFileClick">
          <label></label>
          <input
            ref="file"
            type="file"
            name="image-picker-file"
            id="mage-picker-file"
            @change="onFileChange"
            accept="image/*"
            mutiple="mutiple"
          />
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: "MImagePicker",
  props: {
    title: {
      type: String,
      default: '图片'
    },
    desc: {
      type: String,
      default: ''
    },
    maxLength: {
      type: Number,
      default: 3
    },
    files: {
      type: Array,
      default: () => [],
    },
  },
  computed:{
    imageLength(){
      return  this.files.length > 0 ?  this.files.length: 0
    }
  },
  methods: {
    onFileClick() {
      if(this.imageLength >= this.maxLength) return
      this.$refs.file.click();
    },
    onFileChange(e) {
      this.$emit("onChange", e);
    },
    onImageClick(id) {
      this.files.splice(
        this.files.findIndex((v) => v.id === id),
        1
      );
    },
  },
};
</script>
